package com.link.base.base.knowledge.service;

import com.link.base.user.model.CoreUser;
import com.link.base.base.knowledge.dao.mybatis.mapper.KnowledgeMapper;
import com.link.base.base.knowledge.model.Knowledge;
import com.link.base.base.statistics.model.Statistics;
import com.link.base.base.statistics.service.StatisticsService;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author unknown
 * @date unknown
 * @comments 知识库处理
 */
@Service
public class KnowledgeServiceImpl extends BasicServiceImpl<Knowledge> implements KnowledgeService {

    @Resource
    private KnowledgeMapper knowledgeMapper;
    @Resource
    private StatisticsService statisticsService;

    @Override
    public BasicMapper<Knowledge> getBasicMapper() {
        return knowledgeMapper;
    }

    @Override
    public Knowledge countCollById(Knowledge entity) {
        return knowledgeMapper.countCollById(entity);
    }

    @Override
    public List<Knowledge> queryRoot(Knowledge knowledge) throws Exception {
        return knowledgeMapper.queryRoot(knowledge);
    }

    @Override
    public void queryTreeByRoot(Knowledge root, String publicFlag, long corpId) throws Exception {
        int i = 0;
        Map<String, List<Knowledge>> map = queryAllTree(publicFlag, corpId);
        for (Knowledge entity : root.getChildren()) {
            if (entity != null) {
                entity.setState("closed");
                treeKnowledgeList(entity, root.getPos(), i++, map);
            }
        }

    }

    /**
     * 递归查询知识树结构
     *
     * @throws BasicServiceException
     */
    @Override
    public void treeKnowledgeList(Knowledge entity, int parentPos, int pos, Map<String, List<Knowledge>> map) throws Exception {
        entity.setPageFlag(false);
        entity.setParentId(entity.getId());
        entity.setPos(pos);
        entity.setParentPos(parentPos);
        entity.setSerial((pos + 1) + ".");
        List<Knowledge> tempList = map.get(String.valueOf(entity.getId()));
        if (tempList == null) {
            tempList = new ArrayList<>();
        }
        int i = 0;
        for (Knowledge temp : tempList) {
            treeKnowledgeList(temp, pos, i++, map);
            temp.setSerial(entity.getSerial() + i);
            temp.setState("closed");
        }
        entity.setChildren(tempList);
    }

    @Override
    public List<Knowledge> queryTreeNode(Knowledge t) throws Exception {
        return knowledgeMapper.queryTreeByRoot(t);
    }

    @Override
    public Knowledge queryRootByShareId(Knowledge entity) throws Exception {
        return knowledgeMapper.queryRootByShareId(entity);
    }

    @Override
    public Knowledge queryCorpById(Knowledge entity) throws Exception {
        return knowledgeMapper.queryCorpById(entity);
    }

    @Override
    public List<Knowledge> queryLeafByNode(Knowledge entity) throws Exception {
        return knowledgeMapper.queryLeafByNode(entity);
    }

    @Override
    public Integer increasePageviews(Long id) throws Exception {
        if (null == id) {
            throw new ServiceException("PUBLIC-007");
        }
        Statistics statistics = new Statistics();
        CoreUser user = UserUtil.getUser();
        statistics.setModuleId(id);
        statistics.setModuleName("knowledgeBase");
        statistics.setUserId(user.getId());
        statistics = statisticsService.increasePageView(statistics);
        return statistics.getPageViewNum();
    }

    @Override
    public List<Knowledge> queryKnowledgeTypeNum(Knowledge record) throws Exception {
        return knowledgeMapper.queryKnowledgeTypeNum(record);
    }

    @Override
    public List<Knowledge> queryAppKnowledgeTypeNum(Knowledge record) throws Exception {
        return knowledgeMapper.queryAppKnowledgeTypeNum(record);
    }

    @Override
    public void setStatisticsData(Knowledge record, Long userId) throws Exception {
        // 从Redis中获取知识库的浏览量、阅读人数、点赞量、收藏量
        Statistics statistics = statisticsService.getStatisticsByModuleRecord("knowledgeBase", record.getId());
        record.setCollNum(statistics.getCollectNum());
        record.setPageviews(statistics.getPageViewNum());
        record.setThumbUpNum(statistics.getThumbNum());
        record.setReadNum(statistics.getReadNum());
        // 从Redis中获取用户是否点赞、是否收藏
        if (null != userId) {
            statistics = statisticsService.getFlagByModuleAndUser("knowledgeBase", record.getId(), userId);
            record.setIsColl(statistics.getIsCollect());
            record.setIsThumbUp(statistics.getIsThumb());
        }
    }


    /**
     * 查询 类型KNOWLEDGE_TYPE的值列表 已父id为 key 分组
     * @author yipeng.zhu@hand-china.com
     * @date 2019/1/14 18:52
     * @version 1.0
     */
    public Map<String, List<Knowledge>> queryAllTree(String publicFlag, long corpId) {
        Knowledge entity = new Knowledge();
        Map<String, List<Knowledge>> map = new HashMap<>(16);
        entity.setPageFlag(false);
        if (publicFlag.equals("N")) {
            CoreUser user = UserUtil.getUser();
            entity.setLoginCorpId(user.getCorpid());
        }
        //非登陆树暂时先使用前端指定的账套
        String yes = "Y";
        if (yes.equals(publicFlag)) {
            entity.setLoginCorpId(corpId);
        }
        // entity.setType("KNOWLEDGE_TYPE"); 已弃用一级分类、二级分类，使用目录分类folderPath、folderId
        List<Knowledge> tempList = knowledgeMapper.queryTreeByRoot(entity);
        //已父id为唯一性  去重
        List<Knowledge> list = tempList.stream()
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                        new TreeSet<>(Comparator.comparing(Knowledge::getParentId))), ArrayList::new));
        for (Knowledge knowledge : list) {
            List<Knowledge> knowledgeList = new ArrayList<>();
            for (Knowledge bean : tempList) {
                if (knowledge.getParentId().equals(bean.getParentId())) {
                    knowledgeList.add(bean);
                }
            }
            map.put(String.valueOf(knowledge.getParentId()), knowledgeList);
            //移除已分组后的数据
            tempList = remove(tempList, knowledge.getParentId());
        }
        return map;
    }

    /**
     * 移除 父id 为parentId的数据
     * @author yipeng.zhu@hand-china.com
     * @param list     知识库
     * @param parentId 父id
     * @return
     * @throws
     * @date 2019/1/14 18:55
     * @version 1.0
     */
    public List<Knowledge> remove(List<Knowledge> list, Long parentId) {
        list.removeIf(x -> x.getParentId().equals(parentId));
        return list;
    }

    /**
     * 模糊查询标题内容
     * @author 朱泊阳
     * @param knowledge     知识库
     * @return
     * @throws
     * @date 2019/1/14 18:55
     * @version 1.0
     */
    @Override
    public List<Knowledge> queryKnowledgeByExamplePage(Knowledge knowledge) {
        List<Knowledge> list = knowledgeMapper.queryKnowledgeByExamplePage(knowledge);
        return list;
    }

    /**
     * <p>浏览量pv字段加一，非pageview字段</p>
     * <p>注意：方法名称特意不以update结尾，因为不需要进入mybatis拦截器</p>
     *
     * @author 姚润发
     * @param id 知识库对象id
     * @return
     */
    public int increasePV(Long id) {
        if (id == null) {
            throw new ServiceException("PUBLIC-007");
        }
        return knowledgeMapper.increasePV(id);
    }
}
